package com.cloud.easy.im.utils;

import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 通用线程工厂
 *
 * @author wangjian
 * @version 0.1.0
 * @create 2020年09月25日3:18 下午
 */
public class BasicThreadFactory implements ThreadFactory {

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final Builder builder;

    public BasicThreadFactory(Builder builder) {
        this.builder = builder;
    }

    @Override
    public Thread newThread(@NonNull Runnable runnable) {
        String threadName = String.format(builder.namingPattern, threadNumber.getAndIncrement()) + "-thread-";
        Thread thread = new Thread(runnable, threadName);
        thread.setDaemon(builder.daemon);
        return thread;
    }

    public static class Builder {

        /**
         * 线程名
         */
        private String namingPattern;

        /**
         * 是否守护线程
         */
        private boolean daemon;

        public Builder namingPattern(String namingPattern) {
            this.namingPattern = namingPattern;
            return this;
        }

        public Builder daemon(boolean daemon) {
            this.daemon = daemon;
            return this;
        }

        public BasicThreadFactory build() {
            return new BasicThreadFactory(this);
        }
    }
}
